﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Kooboo.CMS.Form;
using Kooboo.CMS.Form.Html;
using Kooboo.Globalization;
using Kooboo.CMS.Form.Html.Controls;

namespace KB.Controls
{
    public class MediaFile : ControlBase
    {
        private string _name;
        public override string Name
        {
            get
            {
                if (string.IsNullOrEmpty(_name))
                {
                    _name = this.GetType().Name;
                }

                return _name;
            }
        }

        /// <summary>
        /// false
        /// </summary>
        protected virtual bool AllowMultipleFiles
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// /^.+\..+$/
        /// </summary>
        protected virtual string Validation
        {
            get
            {
                return @"/^.+\..+$/";
            }
        }

        protected virtual bool WithDescription
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Please select a valid file
        /// </summary>
        protected virtual string ValidationErrorMessage
        {
            get
            {
                return "Please select a valid file";
            }
        }

        protected override string RenderInput(Kooboo.CMS.Form.IColumn column)
        {
            string script = "<script src=\"@KB.Controls.ControlsScript.GetWebResourceUrl()\" type=\"text/javascript\" ></script>";
            string options = @"{
                allowMultipleFiles: " + AllowMultipleFiles.ToString().ToLower() + @",
                validation: " + Validation + @",
                validationErrorMessage: '" + ValidationErrorMessage + @"'
            }";
            string mediaLibraryUrl = @"@Url.Action(""Selection"", ""MediaContent"", new {
                        repositoryName = Site.Current.Repository,
                        siteName = Site.Current.FullName,
                        FolderName = """ + column.DefaultValue + @"""
                    })";

            var input = String.Format(@"@{{ var data{1} = !string.IsNullOrEmpty( Model.{1} )? string.Join( ""|"", ((string)Model.{1}).Split('|').Select(o=>o.Contains(""."")?  Url.Content(o):"""")) : """" ;}}
                <input id=""{1}"" name=""{1}"" type=""hidden"" value=""@Html.Raw(data{1})"" />
                {0}
                <a id='addMedia_{1}' columnName='{1}' 
                    href='{2}' class='o-icon add'>add</a>
                <script type='text/javascript'>
                    $('#addMedia_{1}').mediaControl{3}({4});
                </script>
            ", script, column.Name, mediaLibraryUrl, WithDescription ? "_Des" : "", options);
            return input;
        }
    }
}